package com.dy.lock.screen.api.servlet;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.dy.lock.screen.api.constants.Constant;
import com.dy.lock.screen.api.scoket.Head;
import com.dy.lock.screen.api.scoket.SocketDTO;
import com.dy.lock.screen.api.scoket.TransmissionCode;
import com.dy.lock.screen.api.utils.CommonUtil;
import com.dy.lock.screen.api.utils.IpUtil;
import com.dy.lock.screen.api.utils.ServletUtil;
import com.dy.lock.screen.api.vo.ResultVo;
import com.dy.lock.screen.api.vo.SoftwareVersionVo;
import com.google.gson.Gson;

/**
 * 
 * @description 获取版本号
 * @author
 * @date
 */
public class GetSoftwareVersionServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger
			.getLogger(GetSoftwareVersionServlet.class);
	private static Gson gson = CommonUtil.gson();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setStatus(HttpServletResponse.SC_OK);

		SocketDTO dto = sendMessage(req);
		Head head = dto.getHead();
		String resCode = head.getResponseCode();
		// String resMsg = head.getResponseMessage();
		String body = dto.getBody();
		if (TransmissionCode.SUCCESS.getCode().equals(resCode)) {
			// 把service中返回的信息转成对应的json格式字符串，返回给接口调用者
			if (StringUtils.isNotBlank(body)) {
				SoftwareVersionVo result = gson.fromJson(body,
						SoftwareVersionVo.class);
				ResultVo ri = new ResultVo();
				ri.setCode(Constant.SUCCESS);
				ri.setStatus(Constant.TRUE);
				ri.setData(result);
				ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
			} else {
				ServletUtil.writeErrorStr(resp);
			}
		} else {
			log.error("内部通信异常，" + head.getResponseMessage());
			ServletUtil.writeErrorStr(resp);
		}
	}

	/**
	 * 向service服务发送请求
	 * 
	 * @param t
	 * @param req
	 * @return
	 */
	private SocketDTO sendMessage(HttpServletRequest req) {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.GET_SOFTWARE_VERSION);
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId("api");
		return super.send(head);
	}
}
